package com.zranger.locationdevice.server;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteOrder;

/**
 * 长度字段修改为小端处理
 *
 * @author kent
 * @date 15-9-2.
 */
public class LengthLittleEndDecoder extends LengthFieldBasedFrameDecoder {

    public LengthLittleEndDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    public LengthLittleEndDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
    }

    public LengthLittleEndDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }

    public LengthLittleEndDecoder(ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(byteOrder, maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }


    @Override
    protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
        buf = buf.order(order);

        /*byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes,0,buf.readableBytes());

        System.out.println(new String(bytes));*/

        long frameLength;
        switch (length) {
            case 1:
                frameLength = buf.getUnsignedByte(offset);
                break;
            case 2: //将包长度倒转处理
                int tempLength = buf.getUnsignedShort(offset);

                String tempStr = Integer.toHexString(tempLength);

                for (int i = tempStr.length(); i < 4; i++) {
                    tempStr = "0" + tempStr;
                }

                //小端转为大端
                String newStr = tempStr.substring(2, 4) + tempStr.substring(0, 2);
                frameLength = Integer.parseInt(newStr, 16);

                break;
            case 3:
                frameLength = buf.getUnsignedMedium(offset);
                break;
            case 4:
                frameLength = buf.getUnsignedInt(offset);
                break;
            case 8:
                frameLength = buf.getLong(offset);
                break;
            default:
                throw new DecoderException();
        }
        return frameLength;
    }
}
